package a.acceltest;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.widget.Toast;

public class MotionDraw extends Activity {
	private SensorManager mSensorManager;
    private Sensor mAcc;
	private Paint mPaint;
	private ArrayList<Path> mGraphics = new ArrayList<Path>();
	public float XX = 0, YY = 0;
	private Path path;
	int cw, ch;
	Bitmap cbmp = null;
	Canvas cnvs = null;
	Matrix IM;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(new SketchView(this));

		mPaint = new Paint();
		mPaint.setDither(true);
		mPaint.setColor(Color.BLACK);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(5);
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	}
	
	private MenuItem item1, item2, item3, item4;
	SubMenu item5;
	private ArrayList<MenuItem> colours = new ArrayList<MenuItem>();
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		item1=menu.add(0, 4, 0,"Switch to Touch");
		item2=menu.add(0, 0, 0, "text2");
		item3=menu.add(0, 2, 0, "text3");
		item4=menu.add(0, 3, 0, "text4");
		item5=menu.addSubMenu("Change Colour");
		colours.add(item5.add(0, 0, 255, "Blue"));
		colours.add(item5.add(143, 0, 255, "Violet"));
		colours.add(item5.add(75, 0, 130, "Indigo"));
		colours.add(item5.add(0, 255, 0, "Green"));
		colours.add(item5.add(255, 255, 0, "Yellow"));
		colours.add(item5.add(255, 127, 0, "Orange"));
		colours.add(item5.add(255, 0, 0, "Red"));
		colours.add(item5.add(0, 0, 0, "Black"));
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item == item1){
			
			Toast.makeText(this, "HA...HA...HA...", Toast.LENGTH_LONG).show();
		}
		for(MenuItem x:colours){
			if(item == x){
				mPaint.setColor(Color.rgb(x.getGroupId(), x.getItemId(), x.getOrder()));
				Toast.makeText(this, x.getTitle(), Toast.LENGTH_LONG).show();
			}			
		}
		return false;
	}
	
	private class SketchView extends SurfaceView implements SurfaceHolder.Callback, SensorEventListener  {
		
		private SketchThread mThread;
		public SketchView (Context context){
			super(context);
			getHolder().addCallback(this);
			mThread = new SketchThread(getHolder(), this);
			setFocusable(true);
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
			
		}

		public void surfaceCreated(SurfaceHolder holder) {
			cw = getWidth();
			ch = getHeight();
			cbmp = Bitmap.createBitmap(cw, ch, Bitmap.Config.ARGB_8888);
			cnvs = new Canvas();
			cnvs.setBitmap(cbmp);
			cnvs.drawColor(Color.WHITE);
			IM = new Matrix();
			mThread.setRunning(true);
			mThread.start();
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			boolean retry = true;
			mThread.setRunning(false);
			while(retry)
			{
				try{
					mThread.join();
					retry = false;
				} catch (InterruptedException e){
				}
			}
		}
		
		@Override
		public void onDraw(Canvas canvas) {
			for (Path path : mGraphics) {
				cnvs.drawPath(path, mPaint);
			}
			try{
			canvas.drawBitmap(cbmp, IM, null);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			mGraphics.clear();
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			synchronized (mThread.getSurfaceHolder()) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
				    mSensorManager.registerListener(this, mAcc, SensorManager.SENSOR_DELAY_NORMAL);
				    path = new Path();
					XX = event.getX();
					YY = event.getY();
					path.moveTo(XX, YY);
				}
				else if(event.getAction() == MotionEvent.ACTION_MOVE){
					}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					mSensorManager.unregisterListener(this);
					}
				return true;
			}
		}
		
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			
		}

		public void onSensorChanged(SensorEvent event) {
			if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
	            return;
	        float mSensorX, mSensorY, XXF, YYF;
	                mSensorX = event.values[0];
	                mSensorY = event.values[1];
	                XX = XX - mSensorX;
	                YY = YY + mSensorY;
					path.lineTo(XX, YY);
					mGraphics.add(path);
		}
	}

	class SketchThread extends Thread {
		private SurfaceHolder mSurfaceHolder;
		private SketchView mSketchView;
		private boolean mRun = false;

		public SketchThread(SurfaceHolder surfaceHolder, SketchView sketchView) {
			mSurfaceHolder = surfaceHolder;
			mSketchView = sketchView;
		}

		public void setRunning(boolean run) {
			mRun = run;
		}

		public SurfaceHolder getSurfaceHolder() {
			return mSurfaceHolder;
		}

		@Override
		public void run() {
			Canvas c;
			while (mRun) {
				c = null;
				try {
					c = mSurfaceHolder.lockCanvas(null);
					synchronized (mSurfaceHolder) {
						mSketchView.onDraw(c);
					}
				} finally {
					if (c != null) {
						mSurfaceHolder.unlockCanvasAndPost(c);
					}
				}
			}
		}
	}
}